package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyCenterService {

    @Autowired
    private UserService userService;

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 步骤1：发送短信验证码
     * @return
     */
    public Boolean sendVerificationCode(String token) {
        //1.根据token查询用户信息
        User user = userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }

        //2.调用smsService发送短信验证码方法
        ErrorResult errorResult = smsService.sendCheckCode(user.getMobile());
        return errorResult == null;
    }

    /**
     * 步骤2：校验验证码
     * @param code
     * @param token
     * @return
     */
    public Boolean checkVerificationCode(String code, String token) {
        //1.根据token查询用户信息
        User user = userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }

        //2.1 生成redis中存储验证码key
        String redisKey = "CHECK_CODE_" + user.getMobile();
        //2.2 调用redisTemplate根据redisKey进行查询 - 结果：redis中保存验证码信息
        String value = redisTemplate.opsForValue().get(redisKey);

        //2.3 比对用户输入的验证码 与 redis中保存验证码
        if(StrUtil.equals(code, value)){
            //2.4 防止验证码重用，将验证码删除
            redisTemplate.delete(redisKey);
            return true;
        }

        return false;
    }

    /**
     * 步骤3：保存新手机号
     * @return
     */
    public Boolean updatePhone(String token, String newPhone) {
        //校验token
        User user = userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }
        //调用userService根据用户id修改手机号方法
        Boolean result = userService.updatePhone(user.getId(), newPhone);
        if(result){
            //防止缓存手机号出现问题，修改成功手机号之后，需要清空对应用户手机号码缓存信息
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            redisTemplate.delete(redisKey);
        }

        return result;
    }

}
